#include "fdlib.h"

InitFD(_fd)
FD*	_fd;
{
	_fd->file = ERROR;
	_fd->size = _fd->bufsiz	= 0;
	_fd->name = _fd->buf	= 0;
}



unsigned SizeFD(_fd)
FD*		_fd;
{
	if (seek(_fd->file,0,LAST) == ERROR)
			trouble("seek LAST in",_fd->name);

	_fd->size = tell(_fd->file);

	if (seek(_fd->file,0,START) == ERROR)
			trouble("seek START in",_fd->name);
	return _fd->size;
}



FILE*	CreatFD(_fd,_mode)
FD*	_fd;
int	_mode;
{
	unlink(_fd->name);

	if ((_fd->file = creat(_fd->name,_mode)) == ERROR)
		trouble("create", _fd->name);
	return _fd->file;
}




FILE*	OpenFD(_fd,_mode)
FD*	_fd;
int	_mode;
{
	if ((_fd->file = open(_fd->name,_mode)) == ERROR)
		trouble("open", _fd->name);
	else SizeFD(_fd);

	return _fd->file;
}



int CloseFD(_fd)
FD*	_fd;
{
	int	result;

	result	= SUCCESS;

	if (_fd->file != ERROR)
	{
		if ((result = close(_fd->file)) == ERROR)
			trouble("close",_fd->name);
	}
	return result;
}



char*	ABufFD(_fd, _size,_fill)
FD*		_fd;
unsigned	_size;
char		_fill;
{
	if (_fd->buf)
	{
		trouble("multiple allocation attempts for",_fd->name);
		return 0;
	}
	else
	{
		_fd->buf = malloc(_size);
		if (_fd->buf)
		{
			_fd->bufsiz = _size;
			setmem(_fd->buf,_size,_fill);
		}
	}
	if (!_fd->buf) trouble("failed to allocate memory for", _fd->name);
	return _fd->buf;
}
